package logic

import (
	"context"
	"fmt"
	"wangwang/models/mysql"
	"wangwang/models/redisinit"
	"wangwang/pkg"

	"wangwang/userrpc/internal/svc"
	"wangwang/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterUserLogic {
	return &RegisterUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterUserLogic) RegisterUser(in *userrpc.RegisterUserRequest) (*userrpc.RegisterUserResponse, error) {
	// todo: add your logic here and delete this line
	get := redisinit.Client.Get("captcharegister" + in.Username)
	if in.Captcha != get.Val() {
		return nil, fmt.Errorf("邮箱验证码错误，请重新输入")
	}
	cmd := redisinit.Client.Get("coderegister" + in.Username)
	if in.Code != cmd.Val() {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	var FindUsers mysql.Users
	mysql.Db.Debug().Where("username = ?", in.Username).Find(&FindUsers)
	if FindUsers.ID != 0 {
		return nil, fmt.Errorf("用户已注册，请重新输入")
	}
	users := mysql.Users{
		Username: in.Username,
		Email:    in.Email,
		Password: pkg.Md5Encryption(in.Password),
	}
	if users.Password != pkg.Md5Encryption(in.Password) {
		return nil, fmt.Errorf("密码不一致，请重新输入")
	}
	mysql.Db.Debug().Create(&users)
	return &userrpc.RegisterUserResponse{Id: int64(users.ID)}, nil
}
